package com.ztorn.controller;

import com.ztorn.dtos.*;
import com.ztorn.model.MyactionLog;
import com.ztorn.model.User;
import com.ztorn.services.AsnService;
import com.ztorn.services.InvService;
import com.ztorn.services.LocationService;
import com.ztorn.services.MyactionLogService;
import com.ztorn.utils.JSONUtil;
import com.ztorn.utils.ScHttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
@Slf4j
public class InboundController {

    @Autowired
    private LocationService locationService;
    @Autowired
    private AsnService asnService;
    @Autowired
    private InvService invService;
    @Autowired
    private MyactionLogService myactionLogService;

    @RequestMapping("/dereliction")
    public ApiResult dereliction(@RequestBody DerParamDTO derParamDTO){
        log.info("无主件请求derParamDTO：{}",JSONUtil.genJson(derParamDTO));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DerDTO der = new DerDTO();
        der.setType("pdd.service.conso.dereliction");
        der.setProviderCode("AFL_HK");
        der.setExecuteTime(simpleDateFormat.format(new Date()));
        der.setTimeZone("UTC+8");
        der.setMailNo(derParamDTO.getMailNo());
        der.setRequestType("dere");
        der.setExpressCode(derParamDTO.getExpressCode());
        der.setDereRecogCode(derParamDTO.getDereRecogCode());
        String dataStr = JSONUtil.genJson(der);
        String resultStr = ScHttpRequestUtil.postHttpurlconnection("https://order.afllogistics.com.hk/service/Gather_gatherInterface.action?token=5884836d2f65258a75dc6a0d8bf154c7", dataStr);
        System.out.printf(resultStr);
        try{
            JSONObject resultJson = JSONObject.fromObject(resultStr);

            Map<String, Class> classMap = new HashMap<String, Class>();
            PddResponseVO responseVO = (PddResponseVO)JSONObject.toBean(resultJson, PddResponseVO.class, classMap);
            PddResponseDetail response = responseVO.getResponse();
            if(response.getCode()==0){
                return ApiResult.ok();
            }
            if(response.getCode() != 0){
                return ApiResult.fail(response.getMessage());
            }
        }catch (Exception e){
            e.printStackTrace();
            return ApiResult.fail(e.getMessage());
        }
        return ApiResult.fail();
    }

    @Transactional
    @RequestMapping("/storage")
    public ApiResult putInStorage(@RequestBody UpParamDTO upParamDTO) {
        log.info("入库上架upParamDTO：{}",JSONUtil.genJson(upParamDTO));
        // 判断库位是否存在
        int exist = locationService.isExistLoc(upParamDTO.getLocalCode());
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        User user = (User)principal;
        if (exist > 0) {
            return doPutInStorage(upParamDTO.getBarCode(), upParamDTO.getLocalCode(),user);
        }else {
            return ApiResult.fail(103, "该库位不存在！");
        }
    }

    public ApiResult doPutInStorage(String asnNos, String location,User user) {
        try {
            // 获取当前用户信息
            String[] orderNoArr = asnNos.split(",");
            asnNos = "";
            for (String orderNo : orderNoArr) {
                asnNos += "'" + orderNo + "',";
            }
            List<MyasnHdrDTO> myasnHdrDTOS = asnService.selectMyasnHdrList(asnNos.substring(0, asnNos.length() - 1), user.getCo());
            String orderNos = "";
            if(CollectionUtils.isEmpty(myasnHdrDTOS)){
                return ApiResult.fail(100,"包裹不存在");
            }
            boolean allThirty = myasnHdrDTOS.stream().allMatch(obj -> obj.getStatCode() == 30);
            List<MyasnHdrDTO> myasnHdrDTOList = new ArrayList<>();
            if(allThirty){
                myasnHdrDTOList.add(myasnHdrDTOS.get(0));
            }else {
                Map<String,Long> orderCountMap = myasnHdrDTOS.stream().collect(Collectors.groupingBy(MyasnHdrDTO::getMiscInstrCode1,Collectors.counting()));
                myasnHdrDTOList = myasnHdrDTOS.stream().filter(order -> order.getStatCode()!=30 || orderCountMap.get(order.getMiscInstrCode1())==1).collect(Collectors.toList());
            }
            for (MyasnHdrDTO dto : myasnHdrDTOList) {
                if (dto.getStatCode() == 20) {
                    dto.setAccount(user.getAccount());
                    orderNos += "'" + dto.getAsnNbr() + "',";
                } else if (dto.getStatCode() == 15) {
                    return ApiResult.fail(101, "包裹未签收");
                } else if (dto.getStatCode() == 30) {
                    if(dto.getUnitAqt()!=null && dto.getUnitQty()!=null && dto.getUnitQty().compareTo(dto.getUnitAqt())==0){
                        return ApiResult.fail(104, "包裹正在被拣货，请放到特定位置");
                    }else if(dto.getUnitQty()!=null && dto.getUnitAqt()==null){
                        MyactionLog myactionLog = new MyactionLog();
                        myactionLog.setWhse(user.getWhse());
                        myactionLog.setCo(user.getCo());
                        myactionLog.setDiv(user.getDiv());
                        myactionLog.setSku(dto.getSku());
                        myactionLog.setToLoc(location);
                        myactionLog.setInvnType(dto.getInvnType());
                        myactionLog.setProdStat(dto.getProdStat());
                        myactionLog.setUnitQty(dto.getUnitQty());
                        myactionLog.setUnitAqt(dto.getUnitAqt());
                        myactionLog.setUnitRqt(0.0);
                        myactionLog.setRefNum1(0.0);
                        myactionLog.setRefNum2(0.0);
                        myactionLog.setOrderNbr(dto.getAsnNbr());
                        myactionLog.setAsnSeqNbr(dto.getAsnSeqNbr());
                        myactionLog.setRevDate(dto.getRevDate());
                        myactionLog.setUserId("JEVIN");
                        myactionLog.setCreateDate(new Date());
                        invService.updateInvLoc(location,dto.getSku(),user.getCo());
                        myactionLogService.save(myactionLog);
                        return ApiResult.ok("包裹货位更新成功", "包裹货位更新成功");
                    }
                }
            }
            if (myasnHdrDTOList != null && myasnHdrDTOList.size() > 0) {
                asnService.putInStorage(orderNos.substring(0, orderNos.length() - 1), location, user.getCo(), myasnHdrDTOList);
                return ApiResult.ok("上架成功", "上架成功");
            }
        }catch (Exception e){
            return ApiResult.fail(500,"上架失败，请联系管理员");
        }
        return ApiResult.fail(103, "CO与订单CO不一致！");
    }
}
